/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.trip;

import beans.user.UserBean;
import database.Database;
import helper.DateProcess;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author daniellesabol
 */
@WebServlet(name = "CreateTripServlet", urlPatterns = {"/CreateTripServlet"})
public class CreateTripServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        UserBean user = (UserBean) request.getSession().getAttribute("userBean");
        //Get Connection
        Connection c = null;
        c = Database.getConnection();
        // YYYY-MM-DD (for year)
        //Is there connection?
        
        String startLocation, endLocation, startDate, endDate, name;
        
      //  ArrayList locations = new ArrayList();
       // ArrayList dates = new ArrayList();
        String locations = "";
        String dates = "";
        
        if (c != null) {
            try {
                //startLocation, endLocation, startDate, endDate, userID, name
                startLocation = request.getParameter("startLocation");
                endLocation = request.getParameter("endLocation");
                startDate = DateProcess.correctDate( request.getParameter("startDate"));
                endDate = DateProcess.correctDate(request.getParameter("endDate"));
                name = request.getParameter("name");
                
                String[] waypointLocations = request.getParameterValues("wayPtLocation"),
                        waypointDates = request.getParameterValues("wayPtDate");
                
                //ADDING START LOCATION / DATE TO ARRAY LISTS
               // locations.add(startLocation + "|");
                locations += startLocation + "|";
               // dates.add(startDate);
                dates += startDate + "|";
                PreparedStatement ps = c.prepareStatement("SELECT id FROM trip ORDER BY id DESC");
                ResultSet psRS = ps.executeQuery();
                int tripId = 1;
                if (psRS.next()) {
                    tripId = psRS.getInt("id") + 1;
                }
                PreparedStatement statement = c.prepareStatement("INSERT INTO trip(startDate,endDate,startLocation,endLocation,userId,name,id) VALUES(?,?,?,?,?,?,?)");
                statement.setString(1, startDate);
                statement.setString(2, endDate);
                statement.setString(3, startLocation);
                statement.setString(4, endLocation);
                statement.setInt(5, user.getId());
                statement.setString(6, name);
                statement.setInt(7, tripId);
                
                try {
                    statement.executeUpdate();
                } catch (SQLException e) { /* do nothing */}
                
                
                int i = 0;
                PreparedStatement wPs = c.prepareStatement("SELECT id FROM waypoint ORDER BY id DESC");
                ResultSet wPsRS = wPs.executeQuery();
                
                int wId = 1;
                if(wPsRS.next()){
                    wId = wPsRS.getInt("id") + 1;
                }
                
                while (i < waypointLocations.length) {
                    //ADDING WAYPOINTS TO THE ARRAY LIST
                   // locations.add(waypointLocations[i] +  "|");
                    locations += waypointLocations[i] + "|";
                   // dates.add(DateProcess.correctDate(waypointDates[i]));
                    dates += DateProcess.correctDate(waypointDates[i]) + "|";
                    
                    PreparedStatement prs = c.prepareStatement("INSERT INTO waypoint(id,location,date,position,tripId) VALUES(?,?,?,?,?)");
                    prs.setInt(1,wId);
                    prs.setString(2, waypointLocations[i]);
                    prs.setString(3, DateProcess.correctDate(waypointDates[i]));
                    prs.setInt(4,i);
                    prs.setInt(5, tripId);
                    wId++;
                    i++;
                    try {
                        prs.executeUpdate();
                    } catch (SQLException e) { /* do nothing */
                       // e.printStackTrace();
                    }
                }
                    locations += endLocation;
                    //dates.add(endDate);
                    dates += endDate;

            } catch (SQLException ex) {
                //Logger.getLogger(CreateAccountServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //pass in trip Id number and redirect to map page
        RequestDispatcher rd = request.getRequestDispatcher("./map_page.jsp"); //this is where you pass the paramater in, but to a servlet
        
        request.getSession().setAttribute("locationList", locations);
        request.getSession().setAttribute("dateList", dates);
      
        rd.forward(request, response);

        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet CreateTripServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet CreateTripServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
